package cn.iocoder.ny.module.mall.utils;

import cn.hutool.core.lang.UUID;
import cn.iocoder.ny.module.mall.config.TySmsConfig;
import cn.iocoder.ny.module.mall.domain.SendCtyunSmsRequest;
import cn.iocoder.ny.module.mall.domain.SmsReport;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;


@Component
public class GetSmsUtils {

    private static TySmsConfig tySmsConfig;

    @Autowired
    public GetSmsUtils(TySmsConfig tySmsConfig) {
        GetSmsUtils.tySmsConfig = tySmsConfig;
    }


    public static String getSms(SendCtyunSmsRequest sendCtyunSmsRequest) {

        // 构造body请求参数
        Map<String, Object> params = buildParams(sendCtyunSmsRequest);
        Gson gson = new GsonBuilder().create();
        String body = gson.toJson(params);
        System.out.println("JSON字符串: " + body);
        try {
            // 构造时间戳
            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            Date now = new Date();
            String signatureTime = timeFormat.format(now);
            String signatureDate = dateFormat.format(now);

            // 构造请求流水号
            String uuId = UUID.randomUUID().toString();

            // 构造待签名字符串
            String campHeader = String.format("ctyun-eop-request-id:%s\neop-date:%s\n", uuId, signatureTime);
            // header的key按照26字母进行排序, 以&作为连接符连起来
            URL url = new URL("https://sms-global.ctapi.ctyun.cn/sms/api/v1");
            String query = url.getQuery();
            StringBuilder afterQuery = new StringBuilder();
            if (query != null) {
                String[] param = query.split("&");
                Arrays.sort(param);
                for (String str : param) {
                    if (afterQuery.length() < 1)
                        afterQuery.append(str);
                    else
                        afterQuery.append("&").append(str);
                }
            }

            // 报文原封不动进行sha256摘要
            String calculateContentHash = getSHA256(body);
            String signatureStr = campHeader + "\n" + afterQuery + "\n" + calculateContentHash;

            // 构造签名
            byte[] kTime = hmacSHA256(signatureTime.getBytes(), tySmsConfig.getAccessKeySecret().getBytes());
            byte[] kAk = hmacSHA256(tySmsConfig.getAccessKeyId().getBytes(), kTime);
            byte[] kDate = hmacSHA256(signatureDate.getBytes(), kAk);
            String signature = Base64.getEncoder().encodeToString(hmacSHA256(signatureStr.getBytes(StandardCharsets.UTF_8), kDate));

            // 构造请求头
            HttpPost httpPost = new HttpPost(String.valueOf(url));
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            httpPost.setHeader("ctyun-eop-request-id", uuId);
            httpPost.setHeader("Eop-date", signatureTime);
            String signHeader = String.format("%s Headers=ctyun-eop-request-id;eop-date Signature=%s", tySmsConfig.getAccessKeyId(), signature);
            httpPost.setHeader("Eop-Authorization", signHeader);

            httpPost.setEntity(new StringEntity(body, ContentType.create("application/json", "utf-8")));

            try (CloseableHttpClient httpClient = HttpClients.createDefault();
                 CloseableHttpResponse response = httpClient.execute(httpPost) ) {
                String result = EntityUtils.toString(response.getEntity(), "utf-8");
                System.out.println(result);
                // 解析JSON字符串
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode rootNode = objectMapper.readTree(result);

                // 提取statusCode
                JsonNode dataNode = rootNode.path("data");
                if (dataNode.isArray() && dataNode.size() > 0) {
                    JsonNode firstItem = dataNode.get(0);
                    String statusCode = firstItem.path("statusCode").asText();
                    return statusCode;
                } else {
                    return null;
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return null;
    }
    /**
     * 构造请求参数
     * @param sendCtyunSmsRequest 请求参数
     * @return Map
     */
    private static Map<String,Object > buildParams(SendCtyunSmsRequest sendCtyunSmsRequest) {
        Map<String, Object> params = new HashMap<>(16);
//        String numbers = randomNumbers(6);
        params.put("action", "QuerySendDetails");
        params.put("phoneNumber", sendCtyunSmsRequest.getPhoneNumber());
        params.put("currentPage", 1);
        params.put("pageSize", 5);
        params.put("signName", "聪明掌柜");
        params.put("templateCode", "SMS11714296487");
        params.put("requestId", sendCtyunSmsRequest.getRequestId());
        params.put("sendDate", sendCtyunSmsRequest.getSendDate());
        return params;
    }


    private static String toHex(byte[] data) {
        StringBuilder sb = new StringBuilder(data.length * 2);
        byte[] var2 = data;
        int var3 = data.length;
        for (int var4 = 0; var4 < var3; ++var4) {
            byte b = var2[var4];
            String hex = Integer.toHexString(b);
            if (hex.length() == 1) {
                sb.append("0");
            } else if (hex.length() == 8) {
                hex = hex.substring(6);
            }
            sb.append(hex);
        }
        return sb.toString().toLowerCase(Locale.getDefault());
    }

    private static String getSHA256(String text) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(text.getBytes(StandardCharsets.UTF_8));
            return toHex(md.digest());
        } catch (NoSuchAlgorithmException var3) {
            return null;
        }
    }

    private static byte[] hmacSHA256(byte[] data, byte[] key) {
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(key, "HmacSHA256"));
            return mac.doFinal(data);
        } catch (Exception e) {
            return new byte[0];
        }



    }
    private static final Random RANDOM = new Random();
    private static final int[] NON_ZERO_DIGITS = {1, 2, 3, 4, 5, 6, 7, 8, 9};

    public static String randomNumbers(int codeNum) {
        if (codeNum < 2) {
            throw new IllegalArgumentException("验证码长度必须大于等于2");
        }

        StringBuilder sb = new StringBuilder(codeNum);

        // 首位数字
        sb.append(NON_ZERO_DIGITS[RANDOM.nextInt(NON_ZERO_DIGITS.length)]);

        // 中间数字
        for (int i = 1; i < codeNum - 1; i++) {
            sb.append(RANDOM.nextInt(10));
        }

        // 尾部数字
        sb.append(NON_ZERO_DIGITS[RANDOM.nextInt(NON_ZERO_DIGITS.length)]);

        return sb.toString();
    }

//    private static final String ACCESS_KEY = "fa002060eebe4df5a90a53788da47518";
//    private static final String SECURITY_KEY = "8489fda5020045ef9e0e9caf3cfbf099";
////    private static final String ACCESS_KEY = "fa002060eebe4df5a90a53788da47518";
////    private static final String SECURITY_KEY = "55643bdb52c74f2e9c269d34ba171b6f";
//    private static final String API_URL = "https://sms-global.ctapi.ctyun.cn/sms/api/v1";
//
//    public static void sendSms(SendCtyunSmsRequest sendCtyunSmsRequest) {
//        Map<String, String> params = buildParams(sendCtyunSmsRequest);
//        Gson gson = new GsonBuilder().create();
//        String body = gson.toJson(params);
//        try {
//            String signatureTime = getFormattedDate("yyyyMMdd'T'HHmmss'Z'");
//            String signatureDate = getFormattedDate("yyyyMMdd");
//            String uuId = UUID.randomUUID().toString().replace("-", "");
//
//            String campHeader = String.format("ctyun-eop-request-id:%s\neop-date:%s\n", uuId, signatureTime);
//            String calculateContentHash = getSHA256(body);
//            String signatureStr = campHeader + "\n" + calculateContentHash;
//
//            String signature = generateSignature(signatureStr, signatureTime, signatureDate);
//
//            // 创建HTTP POST请求
//            HttpPost httpPost = new HttpPost(API_URL);
//            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
//            httpPost.setHeader("ctyun-eop-request-id", uuId);
//            httpPost.setHeader("Eop-date", signatureTime);
//            String signHeader = String.format("%s Headers=ctyun-eop-request-id;eop-date Signature=%s", ACCESS_KEY, signature);
//            httpPost.setHeader("Eop-Authorization", signHeader);
//            httpPost.setEntity(new StringEntity(body, ContentType.create("application/json", "utf-8")));
//
//            try (CloseableHttpClient httpClient = HttpClients.createDefault();
//                 CloseableHttpResponse response = httpClient.execute(httpPost)) {
//                String result = EntityUtils.toString(response.getEntity(), "utf-8");
//                System.out.println("返回结果：" + result);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    private static Map<String, String> buildParams(SendCtyunSmsRequest sendCtyunSmsRequest) {
//        String numbers = randomNumbers(6);
//        Map<String, String> params = new HashMap<>();
//        params.put("action", "SendSms");
//        params.put("phoneNumber", "13382055689");
//        params.put("signName", sendCtyunSmsRequest.getSignName());
//        params.put("templateCode", "SMS11714296487");
//        params.put("templateParam", "{code:"+numbers+"}");
////        params.put("extendCode", sendCtyunSmsRequest.getExtendCode());
//        return params;
//    }
//
//    private static String getFormattedDate(String format) {
//        SimpleDateFormat sdf = new SimpleDateFormat(format);
//        return sdf.format(new Date());
//    }
//
//    private static String getSHA256(String text) {
//        try {
//            MessageDigest md = MessageDigest.getInstance("SHA-256");
//            md.update(text.getBytes(StandardCharsets.UTF_8));
//            return toHex(md.digest());
//        } catch (NoSuchAlgorithmException e) {
//            return null; // 处理异常
//        }
//    }
//    /**
//     * 生成指定长度的数字验证码，首尾不含0
//     *
//     * @param codeNum 验证码长度
//     * @return 生成的验证码
//     */

//
//
//    private static String toHex(byte[] data) {
//        StringBuilder sb = new StringBuilder(data.length * 2);
//        for (byte b : data) {
//            sb.append(String.format("%02x", b));
//        }
//        return sb.toString();
//    }
//
//    private static String generateSignature(String signatureStr, String signatureTime, String signatureDate) {
//        try {
//            byte[] kTime = hmacSHA256(signatureTime.getBytes(StandardCharsets.UTF_8), SECURITY_KEY.getBytes(StandardCharsets.UTF_8));
//            byte[] kAk = hmacSHA256(ACCESS_KEY.getBytes(StandardCharsets.UTF_8), kTime);
//            byte[] kDate = hmacSHA256(signatureDate.getBytes(StandardCharsets.UTF_8), kAk);
//            return Base64.getEncoder().encodeToString(hmacSHA256(signatureStr.getBytes(StandardCharsets.UTF_8), kDate));
//        } catch (Exception e) {
//            return null; // 处理异常
//        }
//    }
//
//    private static byte[] hmacSHA256(byte[] data, byte[] key) {
//        try {
//            Mac mac = Mac.getInstance("HmacSHA256");
//            mac.init(new SecretKeySpec(key, "HmacSHA256"));
//            return mac.doFinal(data);
//        } catch (Exception e) {
//            return new byte[0]; // 处理异常
//        }
//    }
}
